﻿using System.Collections.Generic;
using System.Linq;
using BasicParts;

namespace ParticleMachine
{
    public class ParticleManager
    {
        protected List<Emitter> particleGroups;

        protected Rectangle viewport;

        /// <summary>
        /// Returns all active emitters on screen.
        /// </summary>
        public IEnumerable<Emitter> ActiveEmitters
        { get { return particleGroups.Where(pg => pg.active && pg.inActiveArea); } }

        /// <summary>
        /// Returns all emitters on screen, even inactive ones.
        /// </summary>
        public IEnumerable<Emitter> OnscreenEmitters
        { get { return particleGroups.Where(pg => pg.inActiveArea); } }

        public ParticleManager()
        {
            particleGroups = new List<Emitter>();
        }

        public virtual void Update(int elapsedTime)
        {
            //#if DEBUG
            //foreach (Emitter pg in Vattenspelet.editor.HideInactiveItems
            //    ? particleGroups.Where(p => p.active) : particleGroups)
            //#else
            foreach (Emitter pg in particleGroups.Where(p => p.active))
            //#endif
            {
                if (pg.activeArea.Intersects(viewport))
                {
                    if (!pg.inActiveArea)
                    {
                        pg.inActiveArea = true;
                        pg.SpawnInitialParticles();
                    }
                    else
                        pg.Update(elapsedTime);
                }
                else
                    pg.inActiveArea = false;
            }
        }

        public void Add(Emitter particleEmitter)
        {
            //unnecessary, right?
            //particleGroup.inActiveArea = true;
            particleGroups.Add(particleEmitter);
        }

        public void Remove(Emitter particleEmitter)
        {
            particleGroups.Remove(particleEmitter);
        }

        public void Clear()
        {
            particleGroups.Clear();
        }
    }
}